package com.jokerku.mini.schedule.controller;

import com.jokerku.mini.schedule.domain.EasyResult;
import com.jokerku.mini.schedule.service.IndexService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: guzq
 * @CreateTime: 2023/05/31 11:02
 * @Description: 首页
 * @Version: 1.0
 */
@Controller
public class IndexController {

//    @RequestMapping("index")
//    public String index() {
//        return "index";
//    }

    @Autowired
    private IndexService indexService;

    @RequestMapping("/")
    public void home(HttpServletResponse response) throws IOException {
        response.sendRedirect("/login.html");
    }

    @RequestMapping("/api/login")
    @ResponseBody
    public EasyResult login(HttpServletRequest request, String userName, String pwd) {
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(pwd)) {
            return EasyResult.buildEasyResultError("请输入正确的用户名和密码");
        }
        boolean loginSuccess = indexService.login(request, userName, pwd);
        if (loginSuccess) {
            HttpSession session = request.getSession();//将用户信息放到session域中
            //将当前登录的user2对象放到session域中
            session.setAttribute("loginUser", userName);
        }
        return loginSuccess ? EasyResult.buildEasyResultSuccess("登录成功") : EasyResult.buildEasyResultError("请输入正确的用户名和密码");
    }

    @RequestMapping("/api/logout")
    public void logout(HttpServletResponse response, HttpServletRequest request) throws IOException {
        //session 失效
        request.getSession().invalidate();
        response.sendRedirect("/login.html");
    }
}
